import os
from sqlalchemy import create_engine, text
from venue_booking_system.app.config import config
from datetime import datetime

# --- 配置 ---
ACTIVITY_ORGANIZER_ID = 1 # 管理员创建
ORDER_USER_ID = 2         # 用户2下单
PARTICIPANT_USER_ID = 3   # 用户3报名
# ---

# 获取数据库URI
config_name = os.getenv('FLASK_CONFIG', 'development')
db_uri = config[config_name].SQLALCHEMY_DATABASE_URI
engine = create_engine(db_uri)

print("--- 准备创建一套完整的测试数据 ---")

try:
    with engine.connect() as connection:
        trans = connection.begin()
        print("✅ 数据库连接成功，事务已开始。")

        try:
            # 1. 创建活动
            activity_stmt = text("""
                INSERT INTO activities (title, description, organizer_id, venue_id, start_time, end_time, max_participants, is_free, fee, status, created_at, updated_at)
                VALUES (:title, :description, :organizer_id, 1, :start_time, :end_time, 10, false, 50.00, 'open', NOW(), NOW())
            """)
            activity_data = {
                'title': 'Full Deletion Test Activity',
                'description': 'Activity with order, payment, and participant.',
                'organizer_id': ACTIVITY_ORGANIZER_ID,
                'start_time': datetime(2025, 9, 1, 10, 0, 0),
                'end_time': datetime(2025, 9, 1, 12, 0, 0)
            }
            result = connection.execute(activity_stmt, activity_data)
            activity_id = result.lastrowid
            print(f"✔️ 成功创建活动，ID: {activity_id}")

            # 2. 创建订单
            order_stmt = text("""
                INSERT INTO orders (user_id, venue_id, activity_id, order_type, total_amount, status, created_at, updated_at, booking_date, time_slot)
                VALUES (:user_id, 1, :activity_id, 'activity', 50.00, 'pending', NOW(), NOW(), :booking_date, '10:00-12:00')
            """)
            order_data = {'user_id': ORDER_USER_ID, 'activity_id': activity_id, 'booking_date': datetime(2025, 9, 1).date()}
            result = connection.execute(order_stmt, order_data)
            order_id = result.lastrowid
            print(f"✔️ 成功创建订单，ID: {order_id}")

            # 3. 创建支付记录
            payment_stmt = text("""
                INSERT INTO payments (order_id, user_id, amount, payment_method, status, transaction_id, created_at, updated_at)
                VALUES (:order_id, :user_id, 50.00, 'wechat', 'paid', :transaction_id, NOW(), NOW())
            """)
            payment_data = {'order_id': order_id, 'user_id': ORDER_USER_ID, 'transaction_id': f'txn_{order_id}'}
            connection.execute(payment_stmt, payment_data)
            print(f"✔️ 成功创建支付记录，关联订单ID: {order_id}")
            
            # 4. 创建活动报名记录
            participant_stmt = text("""
                INSERT INTO activity_participants (activity_id, user_id, status, joined_at, created_at, updated_at)
                VALUES (:activity_id, :user_id, 'joined', NOW(), NOW(), NOW())
            """)
            participant_data = {'activity_id': activity_id, 'user_id': PARTICIPANT_USER_ID}
            connection.execute(participant_stmt, participant_data)
            print(f"✔️ 成功创建报名记录，用户ID: {PARTICIPANT_USER_ID}")

            trans.commit()
            print(f"\n✅ 事务提交成功！测试数据已全部创建。活动ID为: {activity_id}")

        except Exception as e:
            print(f"❌ 事务执行失败: {e}")
            trans.rollback()
            print("❌ 事务已回滚。")

except Exception as e:
    print(f"❌ 数据库连接失败: {e}") 